package servlet;

import com.geepi.base.DBUtil;
import net.sf.json.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

public class RegisterServlet extends HttpServlet {

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		request.setCharacterEncoding("UTF-8");
		String account = request.getParameter("account");
		String password = request.getParameter("password");
		String nick = request.getParameter("nick");

		String querySql = String.format("select count(*) from account where account = '%s';", account);
		
		int status = -1;
		String message = "";
		DBUtil dbUtil = new DBUtil();
		boolean isOpen = dbUtil.open();
		if (isOpen == false) {
			status = 102;
			message = "数据库打开失败";
		} else {
			try {
				ResultSet resultSetCount = dbUtil.query(querySql);
				while (resultSetCount.next()) {
					int count = resultSetCount.getInt("count(*)");
					if (count < 1) {
						//inser account info.
						String insertSql = String.format("INSERT INTO account VALUES ('%s', '%s', '%s');", account, password, nick);
						boolean isInsertSuccess = dbUtil.update(insertSql);
						if (isInsertSuccess) {
							status = 0;
							message = "注册成功";
						} else {
							status = 100002;
							message = "注册失败";
						}
					} else {
						status = 0;
						message = "用户已经注册";
					}
				}
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		Map<String, Object> tempParamsMap = new HashMap<String, Object>();
		tempParamsMap.put("status", status);
		tempParamsMap.put("msg", message);
		JSONObject jsonObject = null;		
		jsonObject = JSONObject.fromObject(tempParamsMap);

		response.setContentType("text/html");
		response.setCharacterEncoding("UTF-8");
		PrintWriter out = response.getWriter();
		out.println(jsonObject);
		out.flush(); // 必须有这行，不然页面不会显示
		out.close();
		super.doGet(request, response);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		super.doPost(req, resp);
	}

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	

}
